package ObserverMode.InitialEdition.subject.impl;

import ObserverMode.InitialEdition.observer.Observer;
import ObserverMode.InitialEdition.subject.Subject;

import java.util.ArrayList;

/**
 * @Author Li Cheng
 * @Date 2021/8/12 22:10
 * @Version 1.0
 */
public class WeatherData implements Subject {

    private ArrayList observers; // 用来记录观察者
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() {
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if(i >= 0)
            observers.remove(i);
    }

    /**
     * 当主题发生变化时，调用该方法，以通知所有的观察者
     * 因为观察者都实现了update方法，所以我们知道如何通知它们
     */
    @Override
    public void notifyObservers() {
        for (int i = 0; i<observers.size() ; i++){
            Observer observer  = (Observer) observers.get(i);
            observer.update(temperature,humidity,pressure);
        }
    }

    //当从气象站得到更新观测值时，我们通知观察者
    public void measurementsChanged(){
        notifyObservers();
    }

    //用来测试布告板,实际情况的是从装置中读取实际的值
    public void setMeasurements(float temperature,float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }






}
